package com.kang.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.alibaba.fastjson.JSON;
import com.kang.pojo.AjaxResult;
import com.kang.pojo.GeneralStorage;
import com.kang.pojo.GgeneralStoragePoJo;
import com.kang.pojo.ItemDetail;
import com.kang.pojo.Picking;
import com.kang.pojo.User;
import com.kang.service.AssistService;
import com.kang.service.CategoryService;
import com.kang.service.PickingService;
import com.kang.service.ShopService;
import com.kang.service.UserService;
import com.kang.service.WarehouseService;
import com.kang.until.StoragePDF;
import com.vonechina.entity.page.GeneralStoragePage;
import com.vonechina.entity.page.ItemDetailPage;
import com.vonechina.entity.page.PickingPage;

/**
 * 物品领用控制层
 * 
 * @author zs614
 *
 */
@Controller
@RequestMapping("picking")
@SessionAttributes({ "pickingPage" })
public class PickingController extends com.kang.controller.Controller {
	/**
	 * 物品领用服务层
	 */
	@Resource
	private PickingService pService;
	/**
	 * 通用服务层
	 */
	@Resource
	private AssistService assistService;
	/**
	 * 仓库服务层
	 */
	@Resource
	private WarehouseService warehouseService;
	/**
	 * 用户服务层
	 */
	@Resource
	private UserService userService;
	/**
	 * 物品分类服务层
	 */
	@Resource
	private CategoryService cService;
	/**
	 * 店仓服务层
	 */
	@Resource
	private ShopService shopService;

	/**
	 * 领用记录分页查询
	 * 
	 * @param session
	 * @param model
	 * @param pickingPage
	 *            搜索条件自动封装实体类
	 * @return 返回jsp页面
	 */
	@RequestMapping("listPicking")
	public String listPicking(HttpSession session, Model model, PickingPage pickingPage) {
		initRight(session);
		if (checkRight("查看领用单") != SUCCESS && checkRight("查看全部领用单") != SUCCESS) {
			return "basic/noRight";
		}
		if (checkRight("查看全部领用单") == SUCCESS) {
			pickingPage.setCreatePersonID(null);
		} else {
			pickingPage.setCreatePersonID(userID);
		}
		model.addAttribute("pickingList", pService.listPicking(pickingPage));
		model.addAttribute("shopList", shopService.listAllShop());
		model.addAttribute("cruiseList", assistService.listCruise());
		model.addAttribute("organizationList", assistService.listOrganization());
		model.addAttribute("warehouseList", warehouseService.listAllWarehouse());
		pickingPage.setPageUrl("picking/listPicking.do");
		model.addAttribute("page", pickingPage);
		model.addAttribute("isAdd", checkRight("新增领用单") == SUCCESS);
		return "stockout/picking/listPicking";
	}

	/**
	 * 前往新增领用记录界面
	 * 
	 * @param session
	 * @param model
	 * @return 返回jsp界面
	 */
	@RequestMapping("toAdd")
	public String toAddPicking(HttpSession session, Model model) {
		initRight(session);
		if (checkRight("新增领用单") != SUCCESS) {
			return "basic/noRight";
		}
		model.addAttribute("shopList", shopService.listAllShop());
		model.addAttribute("cruiseList", assistService.listCruise());
		model.addAttribute("organizationList", assistService.listOrganization());
		model.addAttribute("warehouseList", warehouseService.listAllWarehouse());
		model.addAttribute("categoryList", cService.listAllCategory());
		model.addAttribute("userList", userService.listUserByCuirseAndOrg(null, null));
		return "stockout/picking/addPicking";
	}

	/**
	 * 根据邮轮和部门查询用户
	 * 
	 * @param cruiseID
	 *            邮轮ID
	 * @param organizationID
	 *            部门ID
	 * @return 返回json字符串
	 */
	@RequestMapping("loadUserByCruiseAndOrg")
	@ResponseBody
	public String loadUserByCruiseAndOrg(Integer cruiseID, Integer organizationID) {
		List<User> list = userService.listUserByCuirseAndOrg(cruiseID, organizationID);
		return JSON.toJSONString(list);
	}

	/**
	 * 新增领用记录接口
	 * 
	 * @param session
	 * @param picking
	 *            领用记录自动封装实体类
	 * @param itemIds
	 *            领用物品ID数组
	 * @param pickingNumber
	 *            领用物品数量数组
	 * @return 返回json字符串
	 */
	@RequestMapping("addPicking")
	@ResponseBody
	public String addPicking(HttpSession session, Picking picking, Integer[] itemIds, Integer[] pickingNumber) {
		AjaxResult result = new AjaxResult();
		initRight(session);
		if (checkRight("新增领用单") != SUCCESS) {
			result.setResult("noRight");
			return JSON.toJSONString(result);
		}
		picking.setPickingNumber(pService.generatePickingNumber());
		picking.setCreatePersonID((Integer) session.getAttribute("userID"));
		picking.setLastPersonID((Integer) session.getAttribute("userID"));
		int a = pService.insertPicking(picking);
		if (a > 0) {
			pService.savePickingItem(picking, itemIds, pickingNumber);
			if (picking.getStatus() == 1) {
				pService.submitPicking(picking.getPickingID(), userID);
			}
			result.setResult("success");
		}
		return JSON.toJSONString(result);
	}

	/**
	 * 查看可领用物品接口
	 * 
	 * @param page
	 *            搜索参数自动封装
	 * @return 返回json字符串
	 */
	@RequestMapping("listNotAddItem")
	@ResponseBody
	public String listNotAddItem(ItemDetailPage page) {
		AjaxResult result = new AjaxResult();
		List<ItemDetail> list = pService.listItemNotIn(page);
		result.setTotal(page.getRows());
		result.setRows(list);
		return JSON.toJSONString(result);
	}

	/**
	 * 查看领用记录详情
	 * 
	 * @param request
	 * @param response
	 * @param session
	 * @param model
	 * @param pickingID
	 * @return 返回jsp页面
	 * @throws Exception
	 */
	@RequestMapping("detail")
	public String pickingDetail(HttpServletRequest request, HttpServletResponse response, HttpSession session,
			Model model, Integer pickingID) throws Exception {
		initRight(session);
		Picking picking = pService.selectPickingByID(pickingID);
		if (picking == null) {
			response.sendRedirect(request.getContextPath() + "/picking/listPicking.do");
			return null;
		}
		if (picking.getCreatePersonID() == userID && checkRight("查看领用单") == SUCCESS) {
			model.addAttribute("isEdit", checkRight("新增领用单") == SUCCESS && picking.getStatus() == 0);
		} else if (checkRight("查看全部领用单") == SUCCESS) {
			model.addAttribute("isEdit", checkRight("编辑全部领用单") == SUCCESS && picking.getStatus() == 0);
		} else {
			return "basic/noRight";
		}
		model.addAttribute("shopList", shopService.listAllShop());
		model.addAttribute("cruiseList", assistService.listCruise());
		model.addAttribute("organizationList", assistService.listOrganization());
		model.addAttribute("warehouseList", warehouseService.listAllWarehouse());
		model.addAttribute("categoryList", cService.listAllCategory());
		model.addAttribute("userList", userService.listUserByCuirseAndOrg(null, null));
		model.addAttribute("picking", picking);
		model.addAttribute("items", pService.listPickingItem(pickingID));
		return "stockout/picking/pickingDetail";
	}

	/**
	 * 更新未提交领用记录
	 * 
	 * @param session
	 * @param picking
	 *            领用记录自动封装实体类
	 * @param itemIds
	 *            领用物品ID数组
	 * @param pickingNumber
	 *            领用物品数量数组
	 * @param isSubmit
	 *            是否提交，1=提交
	 * @return 返回josn字符串
	 */
	@RequestMapping("updatePicking")
	@ResponseBody
	public String updatePicking(HttpSession session, Picking picking, Integer[] itemIds, Integer[] pickingNumber,
			Integer isSubmit) {
		AjaxResult result = new AjaxResult();
		initRight(session);
		Picking p = pService.selectPickingByID(picking.getPickingID());
		if (checkRight("新增领用单") == SUCCESS && p.getCreatePersonID() == userID) {
		} else if (checkRight("编辑全部领用单") == SUCCESS) {

		} else {
			result.setResult("noRight");
			return JSON.toJSONString(result);
		}
		picking.setLastPersonID((Integer) session.getAttribute("userID"));
		int a = pService.updatePicking(picking);
		pService.savePickingItem(picking, itemIds, pickingNumber);
		if (a > 0) {
			if (isSubmit != null && isSubmit == 1) {
				pService.submitPicking(picking.getPickingID(), userID);
			}
			result.setResult("success");
		}
		return JSON.toJSONString(result);
	}

	/**
	 * 提交领用记录
	 * 
	 * @param session
	 * @param pickingID
	 *            领用记录ID
	 * @return 返回json字符串
	 */
	@RequestMapping("submitPicking")
	@ResponseBody
	public String submitPicking(HttpSession session, Integer pickingID) {
		AjaxResult result = new AjaxResult();
		initRight(session);
		Picking p = pService.selectPickingByID(pickingID);
		if (checkRight("新增领用单") == SUCCESS && p.getCreatePersonID() == userID) {
		} else if (checkRight("编辑全部领用单") == SUCCESS) {

		} else {
			result.setResult("noRight");
			return JSON.toJSONString(result);
		}
		int a = pService.submitPicking(pickingID, userID);
		if (a > 0) {
			result.setResult("success");
		}
		return JSON.toJSONString(result);
	}

	/**
	 * 删除未提交领用记录
	 * 
	 * @param session
	 * @param pickingID
	 *            领用记录ID
	 * @return 返回json字符串
	 */
	@RequestMapping("deletePicking")
	@ResponseBody
	public String deletePicking(HttpSession session, Integer pickingID) {
		AjaxResult result = new AjaxResult();
		initRight(session);
		Picking p = pService.selectPickingByID(pickingID);
		if (checkRight("新增领用单") == SUCCESS && p.getCreatePersonID() == userID) {
		} else if (checkRight("编辑全部领用单") == SUCCESS) {

		} else {
			result.setResult("noRight");
			return JSON.toJSONString(result);
		}
		int a = pService.deletePicking(pickingID);
		if (a > 0) {
			result.setResult("success");
		}
		return JSON.toJSONString(result);
	}
	
	/**
	 * 导出领料归还PDF文件
	 * 
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("downloads")
	public void downloadPDF(HttpServletResponse response, PickingPage page)
			throws Exception {
		//GeneralStorage gStorage = pService.selectoneid(warehousenumber);
		List<Picking> pkList = pService.listPicking(page);// 查询采购入库数据集合
		System.out.println("======PickingPage========"+page);
		//此方法为直接下载文件
		//File file = WarehouseOrderPDF.buildWarehouseOrderPDF(warehouseOrder, pOrderItem);
		File file = StoragePDF.PickingPDF(pkList);
		if (file.isFile() && file.exists()) {
			try {
				 InputStream fis = new BufferedInputStream(new FileInputStream(file));
				    byte[] buffer = new byte[fis.available()];
				    fis.read(buffer);
				    fis.close();
				    response.reset();
				    //乱码处理
				    //先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名
				    response.addHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().replaceAll(" ", "").getBytes("utf-8"),"iso8859-1"));
				    response.addHeader("Content-Length", "" + file.length());
				    OutputStream os = new BufferedOutputStream(response.getOutputStream());
				    response.setContentType("application/octet-stream");
				    os.write(buffer);//输出文件
				    os.flush();
				    os.close();//关闭流，释放资源！
			} catch (Exception e) {
				e.printStackTrace();
			}
			file.delete();
		}
	}
	
	

}
